package com.yaodian100.mall.cobranding.web;

import java.net.URLEncoder;
import java.util.Date;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.apache.struts2.ServletActionContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.yaodian100.core.common.utils.ServerValue;
import com.yaodian100.ec.cobranding.Onlylady;
import com.yaodian100.ec.member.entity.Balance;
import com.yaodian100.ec.member.entity.Member;
import com.yaodian100.ec.member.service.MemberService;
import com.yaodian100.ec.order.entity.Orders;
import com.yaodian100.ec.order.service.OrderService;
import com.yaodian100.ec.shopping.entity.CartOrderProduct;
import com.yaodian100.ec.shopping.entity.CartOrderProductDetail;
import com.yaodian100.ec.shopping.entity.CartOrders;
import com.yaodian100.ec.shopping.service.CartOrdersService;
import com.yaodian100.mall.member.util.UserData;

public class CoBrandingAction extends ActionSupport {

	/**
	 * 
	 */
	private static final long serialVersionUID = -3518691191612981208L;
	private final Logger LOGGER = LoggerFactory.getLogger(getClass());

	@Autowired
	private OrderService orderService;
	@Autowired
	private MemberService memberService;
	@Resource
	private CartOrdersService cartOrdersService;

	private String orderId;
	// private String memberId;
	// private String loginId;
	private String coBrand;
	private String sendTo;

	private Member member;

	public String memberLogin() {
		HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);
		HttpServletResponse response = (HttpServletResponse) ActionContext.getContext().get(
				ServletActionContext.HTTP_RESPONSE);
		UserData userData = new UserData(request, response);
		String domainSrc = request.getServerName();

		try {
			if ("onlylady".equals(coBrand) || coBrand.endsWith("onlylady.com")) {
				setCoBrand("onlylady");
				Onlylady ol = new Onlylady();
				Cookie[] cookies = request.getCookies();
				String useAgent = request.getHeader("User-Agent");
				String ip = request.getRemoteAddr();
				// String ip = "220.130.152.30";

				StringBuffer cookieStr = new StringBuffer();
				if (null != cookies) {

					for (int i = 0; i < cookies.length; i++) {
						if (cookieStr.length() > 0) {
							cookieStr.append("&");
						}
						String key = cookies[i].getName();
						String value = cookies[i].getValue();
						cookieStr.append(key);
						cookieStr.append("=");
						cookieStr.append(value);
					}
				}
				String cookieStrEncode = cookieStr.toString();
				cookieStrEncode = URLEncoder.encode(cookieStr.toString(), "UTF-8");

				JSONObject resJ = JSONObject.fromObject(ol.olLogin(cookieStrEncode, ip, useAgent));
				JSONObject resM = JSONObject.fromObject(ol.olGetEmail(cookieStrEncode, ip, useAgent));

				String statusJ = resJ.getString("status");
				String statusM = resJ.getString("status");
				if ("0".equals(statusJ) && "0".equals(statusM)) {

					JSONObject objectUserNm = resJ.getJSONObject("object");
					JSONObject objectUserEmail = resM.getJSONObject("object");
					String username = "";
					String email = "";
					try {
						username = objectUserNm.getString("username");
						email = objectUserEmail.getString("email");
					} catch (Exception e) {

					}
					LOGGER.info("paramStr:" + username + ",sendTo", sendTo);
					Member loginMember = setMemberData(username, email, request.getRemoteAddr(), request.getServerName());
					if (null != loginMember) {
						userData.setLoginId(loginMember.getLoginId());
						userData.setMemberId(loginMember.getMemberId());
						userData.setNickname(loginMember.getLoginId());
						// request.setAttribute("member", member);
						setMember(loginMember);
						setSendTo(sendTo);
						CartOrders cartOrders = cartOrdersService.getCart(loginMember.getMemberId(), null);
						if (cartOrders == null) {
							cartOrders = cartOrdersService.createCart(loginMember.getMemberId(), null, null, null, 0, null, null);
						}
						String tmpCartid = StringUtils.defaultString(userData.readRawValue("cartid"));

						processMoveTmpCartToCartOrder(tmpCartid, cartOrders.getCartId(), cartOrdersService, userData);
						// 记录购物车商品数量
						cartOrders = cartOrdersService.get(cartOrders.getCartId());
						userData.writeRawValue(UserData.NAME_YAODIAN100_CART_ITEMS, String.valueOf(cartOrders.getProductSum()));

						// response.sendRedirect(sendTo);
					} else {
						// setCoBrand("onlylady2");
						// request.setAttribute("paramStr", resJ.toString());
						setSendTo("http://passport.onlylady.com/?goto=" + URLEncoder.encode(sendTo, "utf-8"));
						LOGGER.info(sendTo);
						// request.setAttribute("sendTo", "http://passport.onlylady.com/");
						// response.sendRedirect("http://passport.onlylady.com/");
					}
				} else {
					// setSendTo("http://passport.onlylady.com/?goto=" + sendTo);
					// setCoBrand("onlylady2");
					// request.setAttribute("paramStr", resJ.toString());
					String cobrandingLogin = "http://" + domainSrc + "/" + ServerValue.getFrontContextPath()
							+ "/cobranding/memberLogin.do?coBrand=" + domainSrc + "&sendTo=";
					// cobrandingLogin = URLEncoder.encode(cobrandingLogin, "utf-8");
					String pathparam = cobrandingLogin + URLEncoder.encode(sendTo, "utf-8");

					setSendTo("http://passport.onlylady.com/?goto=" + URLEncoder.encode(pathparam, "utf-8"));
					LOGGER.info(sendTo);
					// request.setAttribute("sendTo", "http://passport.onlylady.com/");
					// response.sendRedirect("http://passport.onlylady.com/");
				}
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return coBrand;
		// return "sendTo";
	}

	private void processMoveTmpCartToCartOrder(String tmpCartid, String memberCartId,
			CartOrdersService cartordersService, UserData userData) throws Exception {
		// 若memberCartId為空，則新增一個cartOrders
		// logger.info("memberCartId:{}", memberCartId);
		CartOrders cartOrders = null;
		if (memberCartId == null) {
			cartOrders = cartordersService.createCart(userData.getMemberId(), null, null, null, 0, null, null);
			memberCartId = cartOrders.getCartId();
			userData.writeRawValue("cartid", cartOrders.getCartId());
			// memberCartId = createNewCartOrders(memberCartId, userData);
		} else {
			cartOrders = cartordersService.getCart(memberCartId, null);
		}
		// logger.info("cartOrders:{}", cartOrders);
		if (StringUtils.isNotBlank(tmpCartid)) {
			CartOrders tmpCart = cartordersService.get(tmpCartid);
			if (null != tmpCart) {

				// 將暫存的車移至cartOrderProduct
				for (CartOrderProduct cop : tmpCart.getCartOrderProducts()) {

					boolean isItemExists = false;
					for (CartOrderProduct memberCop : cartOrders.getCartOrderProducts()) {
						if (cop.getProdId().equals(memberCop.getProdId()) && cop.getProdSpecId().equals(memberCop.getProdSpecId())) {
							isItemExists = true;
							break;
						}
					}
					if (!isItemExists) {
						CartOrderProduct tmpcop = new CartOrderProduct();
						// tmpcop.setAmount(new BigDecimal(0.00));
						BeanUtils.copyProperties(cop, tmpcop, new String[] { "cartOrderProdId", "cartOrder", "coupon",
								"modifyDate", "details" });
						// logger.info("tmpcop:{}", tmpcop.getAmount());
						cartOrders.addCartOrderProduct(tmpcop);
						for (CartOrderProductDetail detail : cop.getDetails()) {
							CartOrderProductDetail cloneDetail = new CartOrderProductDetail();
							BeanUtils.copyProperties(detail, cloneDetail, new String[] { "cartOrderDetailId", "cartOrderProdId",
									"orderProduct", "cartId", "cartOrder", "modifyDate", "details" });
							tmpcop.addDetail(cloneDetail);

						}
					}
				}
				// 刪除暫存車的cartOrders
				cartordersService.save(cartOrders);
				cartordersService.delete(tmpCart);
			}
		}
	}

	private Member setMemberData(String loginId, String email, String clientIp, String domainSrc) {

		Member loginMember = null;
		if ("onlylady".equals(coBrand) || coBrand.endsWith("onlylady.com")) {
			setCoBrand("onlylady");
			loginMember = memberService.getMemberByLoginId(loginId, domainSrc);
			if (null == loginMember) {
				loginMember = createMember(loginId, email, clientIp, domainSrc, "onlylady");
			} else {
				if (!email.equalsIgnoreCase(loginMember.getEmail())) {
					loginMember.setEmail(email);
					memberService.updateMember(loginMember);
				}
			}

		}
		return loginMember;

	}

	private Member createMember(String loginId, String email, String clientIp, String domainSrc, String applySource) {
		Member entity = new Member();
		entity.setRank("1");
		entity.setStatus("00");
		entity.setApplySource(applySource);
		entity.setActiveDate(new Date());
		entity.setLoginId(loginId);
		entity.setPwd("xx");
		entity.setEmail(StringUtils.defaultIfEmpty(email, "onlylady@yaodian100.com"));
		entity.setClientIp(clientIp);
		entity.setDomainSrc(domainSrc);
		entity = memberService.save(entity);

		Balance balance = memberService.newBalance(entity);

		return entity;

	}

	public String createOrder() {
		HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);
		if (!StringUtils.isBlank(orderId)) {
			Orders order = orderService.get(orderId);
			if ("onlylady".equals(coBrand) || coBrand.endsWith("onlylady.com")) {
				setCoBrand("onlylady");
				Onlylady ol = new Onlylady();
				request.setAttribute("paramStr", ol.olCreateOrder(order));

			}
		}
		return coBrand;

	}

	public String cancelOrder() {
		HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);
		if (!StringUtils.isBlank(orderId)) {
			Orders order = orderService.get(orderId);
			if ("onlylady".equals(coBrand) || coBrand.endsWith("onlylady.com")) {
				setCoBrand("onlylady");
				Onlylady ol = new Onlylady();
				request.setAttribute("paramStr", ol.olCancelOrder(order));

			}
		}

		return coBrand;
	}

	public String returnOrder() {
		HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);
		if (!StringUtils.isBlank(orderId)) {
			Orders order = orderService.get(orderId);
			if ("onlylady".equals(coBrand) || coBrand.endsWith("onlylady.com")) {
				setCoBrand("onlylady");
				Onlylady ol = new Onlylady();
				request.setAttribute("paramStr", ol.olReturnOrder(order));

			}
		}

		return coBrand;
	}

	public String completeOrder() {
		HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);
		if (!StringUtils.isBlank(orderId)) {
			Orders order = orderService.get(orderId);

			if ("onlylady".equals(coBrand) || coBrand.endsWith("onlylady.com")) {
				setCoBrand("onlylady");
				Onlylady ol = new Onlylady();
				request.setAttribute("paramStr", ol.olCompleteOrder(order));

			}
		}

		return coBrand;
	}

	public String getOrderId() {
		return orderId;
	}

	public void setOrderId(String orderId) {
		this.orderId = orderId;
	}

	// public String getMemberId() {
	// return memberId;
	// }
	//
	// public void setMemberId(String memberId) {
	// this.memberId = memberId;
	// }
	//
	// public String getLoginId() {
	// return loginId;
	// }
	//
	// public void setLoginId(String loginId) {
	// this.loginId = loginId;
	// }

	public String getCoBrand() {
		return coBrand;
	}

	public void setCoBrand(String coBrand) {
		this.coBrand = coBrand;
	}

	public String getSendTo() {
		return sendTo;
	}

	public void setSendTo(String sendTo) {
		this.sendTo = sendTo;
	}

	public Member getMember() {
		return member;
	}

	public void setMember(Member member) {
		this.member = member;
	}

	// public String getOlAction() {
	// return olAction;
	// }
	//
	// public void setOlAction(String olAction) {
	// this.olAction = olAction;
	// }

	// public String getOlParams() {
	// return olParams;
	// }
	//
	// public void setOlParams(String olParams) {
	// this.olParams = olParams;
	// }

}
